package com.ruoyi.user.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.ruoyi.common.core.utils.uuid.UUID;
import org.springframework.web.multipart.MultipartFile;

public class AliPicUtils {
    public static String upload(MultipartFile file) throws Exception {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称，例如examplebucket。
        String filename = file.getOriginalFilename();
        String substring = filename.substring(filename.lastIndexOf("."));
        String string = UUID.randomUUID().toString();
        String bucketName = "jipengimg";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "test"+string+substring;
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。f

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);


            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName,file.getInputStream() );

            PutObjectResult result = ossClient.putObject(putObjectRequest);

                ossClient.shutdown();
        //https://jipengimg.oss-cn-beijing.aliyuncs.com/c28a15e41e4c193e20083410903fa3e.jpg
        return  "https://jipengimg.oss-cn-beijing.aliyuncs.com/"+objectName;

    }
}
